<?php
//默认前台控制器
class userController extends webpageController{
    protected $layout = "passport/user/layout";
    //网站首页
    //###########################################
    public function index(){
        if($this->isPost()){
            $account = $_POST['account'];
            $password = $_POST['password'];
            $msg = Check::rule(
                array( Check::must($account), '请输入登录帐号') ,
                array( Check::must($password), '请输入密码')
                );
            if(true !== $msg){
                $this->jsonMsg($msg);
            }
            //数据库操作
            $rel = model('user')->setLogin($account,$password);
            if($rel === 0){
                $this->jsonMsg('帐号不存在或密码错误');
            }elseif($rel === -1){
                $this->jsonMsg('用户被锁定,禁止登录');
            }else{
                $this->jsonMsg('欢迎您,登录成功.',1,url('passport/index'));
            }
        }else{
            $this->display('passport/user/login');
        }       
    }
    //重置密码
    public function getpassword(){
        if ($this->isPost()) {
            $account = $_POST['account'];
            $getcode = $_POST['getcode'];
            $msg = Check::rule(
                array(Check::must($account), '请输入找回密码帐号.'),
                array(check::must($getcode), '找回方式没有填写.')
                );
            if(true !== $msg){
                $this->jsonMsg($msg);
            }
            $condition['username'] = $account;
            if(check::email($getcode)){
                $condition['email'] = $getcode;
                $rel = model('passport')->find($condition,'email,username,locks,id');
            }elseif(check::mobile($account)){
                $condition['iphone'] = $getcode;
                $rel = model('passport')->find($condition,'iphone,username,locks,id');
            }else{
                $this->jsonMsg('输入找回方式手机或信箱格式错误');
            }
            if(!$rel){
                $this->jsonMsg('输入帐号不存在');
            }
            if($rel['locks'] == 1){
                $this->jsonMsg('帐号已被锁定禁止操作');
            }
            if(check::email($getcode)){
                $newpass = getcode(12);
                $emailadd     =  $rel['email']; 
                $emailtitle   = '尊敬的会员：['. $rel['username'].']您的帐号新密码重置信息';
                $emailcontent = model('passport')->emailContent($newpass,$rel['username']);
                Email::init(config());
                $result = Email::send($emailadd, $emailtitle, $emailcontent);
                if($result){
                    $data = array();
                    $data['restpass'] = 1;
                    $data['restcode'] = $newpass;
                    $data['restdate'] = time();
                    model('passport')->update(array('id'=>$rel['id']),$data);
                    setcookie("newpass",$newpass,time() + 3600,'/');
                    $this->jsonMsg('找回密码请求提交成功,您查看您的信箱!',1,url('user/index'));
                }else{
                    $this->jsonMsg('找回密码邮件发送失败',1,url('user/getpassword'));
                }
            }else{
                $this->jsonMsg('暂不支持手机找回密码');
            }
        }else{
            $this->display('passport/user/getpassword');
        }      
    }
    //重置密码
    public function getpasswordcode(){
        if ($this->isPost()) {//获取数据
            $msg = Check::rule(
                array(check::must($_POST['password']), '修改新密码没有填写'),
                array(check::same($_POST['password'], $_POST['checkpassword']), '两次密码输入不同,请重新输入')
            );
            if(true !== $msg){
                $this->jsonMsg($msg);
            }
            $data = array();
            $data['password']=md5($_POST['password']);
            $data['restpass'] = null;
            $data['restcode'] = null;
            setcookie("newpass","",time() - 3600,'/');
            unset ($_COOKIE['newpass']);
            $verifystr = in($_POST['code']);
            $result = model('passport')->update(array('restcode'=>$verifystr,'restpass'=>1),$data);
            if($result){
                $this->jsonMsg('新密码已经成功修改！.',1,url('user/index'));
            }else{
                $this->jsonMsg('修改失败！请重新找回密码.',1,url('user/getpassword'));
            }             
        }else{
            $newpass = $_COOKIE['newpass']; //本机安全码
            $verifystr = in($_GET[verifystr]);
            if($newpass == $verifystr){ 
                $condition['restcode'] = $verifystr;
                $condition['restpass'] = 1;
                $info = model('passport')->find($condition,'restdate');
                if($info){
                    $locktime = $info['restdate'] + 3600;
                    $nowtime = time();
                    if ($nowtime >= $locktime){
                        $this->PageMsg('找回密码操作超时!',0,url('user/getpassword'));
                    }
                    $this->assign('newpass',$verifystr);
                    $this->display('passport/user/getpasswordcode');
                }else{
                   $this->redirect(url('index/getpassword'));
                }
            }else{
                $this->redirect(url('user/getpassword'));
            }  
        }
    }
    //注册
    public function register(){
        if($this->isPost()){
            $msg = Check::rule(
                array(check::must($_POST['account']), '账户名称没有填写'),
                array(check::must($_POST['password']), '密码没有填写'),
                array(check::must($_POST['checkpassword']), '确认密码没有填写'), 
                array(check::same($_POST['password'], $_POST['checkpassword']), '两次密码输入不相同')
            );
            if ($msg !== true) {
                $this->jsonMsg($msg);
            }
            $data['username'] = $_POST['account'];
            $data['password'] = md5($_POST['password']);
            $data['safepassword'] = md5($_POST['password']);
            $data['reg_time'] = time();
            $result = model('passport')->insert($data);
            if($result){
                $this->jsonMsg('注册成功,点击确认登录',1,url('user/index'));
            }else{
                $this->jsonMsg('注册失败!请重新确认注册.');
            }
        }else{
            $this->display('passport/user/register');
        }
    }
//退出登录
    public function logout() {
        model('user')->logout(); //清楚登录信息
        $callback = $_GET['callback'];
        if($callback){
            $this->redirect($callback);
        }
        $this->redirect(__ROOT__.'/');
    } 
    //验证码
    public function verify(){
        $code = getcode(4);
        Image::buildImageVerify(70,33,$code);
    }
    //检测帐号
    public function valid(){
        $param = trim($_POST['param']);
        $condition['username'] = $param;
        $rel = model('passport')->find($condition,'username');
        if($rel){
            $info['info'] = '帐号已存在,请更换.';
            $info['status'] = 'n';
        }else{
            $info['info'] = '帐号可以使用.';
            $info['status'] = 'y';
        }
        echo json_encode($info);
    }
    //验证码
    public function checkcode(){
        $checkcode = trim($_POST['param']);
        if ($checkcode != $_SESSION['verify']) {
            $info['info'] = '请重新输入';
            $info['status'] = 'n';
        }else{
            $info['info'] = '通过验证.';
            $info['status'] = 'y';
        }
        echo json_encode($info);
    } 
    //第三方帐号登录
    public function openid(){
        $api = in($_GET['api']);
        if($api == 'qq'){
            $qq_state = getcode();
            $_SESSION['qq_state'] = $qq_state;
            $callback_url = 'http://'.config('OPENID_CALLBACK').url('user/qq_callback'); //回调网址
            $login_url = model('qq')->login_url($callback_url); //生成登录链接
            $this->redirect($login_url);
        }elseif($api == 'sina'){
            $weibo_state = getcode();
            $_SESSION['weibo_state'] = $weibo_state;
            $callback_url = 'http://'.config('OPENID_CALLBACK').url('user/sina_callback'); //回调网址
            $login_url = model('sina')->login_url($callback_url,$weibo_state); //生成登录链接
            $this->redirect($login_url);
        }
    }
    //QQ登录成功回调网站
    public function qq_callback(){
        if(isset($_GET['code']) && $_GET['code']!=''){
            $state = $_GET['state'];
            if (empty($state) || $state !== $_SESSION['qq_state']) {
                $this->PageMsg('很抱歉,您要访问的页面不存在!');
            }
            unset($_SESSION['qq_state']);
            $callback_url = 'http://'.config('APP_CALLBACK').url('ucenter/openid/qq_callback');
            $result = model('qq')->access_token($callback_url, $_GET['code']); //获取access_token
        }else{
            $this->PageMsg('很抱歉,您要访问的页面不存在!');
        }
    }
//Sina登录成功回调网站
    /**
     * $result['access_token']，用于调用access_token，接口获取授权后的access token。
     * $result['expires_in']，access_token的生命周期，单位是秒数。 
     * $result['remind_in']，access_token的生命周期（该参数即将废弃，开发者请使用expires_in）。 
     * $result['uid ']，当前授权用户的UID。 
    */
    public function sina_callback(){
        if(isset($_GET['code']) && $_GET['code']!=''){
            $state = $_GET['state'];
            if (empty($state) || $state !== $_SESSION['weibo_state']) {
                $this->PageMsg('很抱歉,您要访问的页面不存在!');
            }
            unset($_SESSION['weibo_state']);
            $callback_url = 'http://'.config('APP_CALLBACK').url('user/sina_callback');
            $result = model('sina')->access_token($callback_url, $_GET['code']); //获取access_token
        }else{
            $this->PageMsg('很抱歉,您要访问的页面不存在!');
        }
    }
}